<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="displayModuleTitle"
    width="1000px"
    @cancel="opSuccess"
  >
    <a-form
      ref="formRef"
      :model="hazardBasicInfo"
      :label-col="{ style: 'width: 130px' }"
      style="margin-top: 20px"
    >
      <a-row>
        <a-col :span="11">
          <a-form-item label="辨识/发现日期" name="tm" :rules="[{ required: true }]">
            <a-date-picker v-model:value="hazardBasicInfo.tm" valueFormat="YYYY-MM-DD" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="辨识/发现人员" name="username" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.username" />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="单元" name="unitname" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.unitname" disabled />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="具体部位" name="position">
            <a-input v-model:value="hazardBasicInfo.position" />
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="类别" name="categorycode" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.categoryname" disabled v-if="mode !== 'add'" />
            <a-select
              v-else
              :fieldNames="{ label: 'name', value: 'code' }"
              v-model:value="hazardBasicInfo.categorycode"
              :options="hazardOptions.filter((item) => item.level == 1)"
              @change="
                (e) => {
                  hazardBasicInfo.projectcode = '';
                  hazardBasicInfo.itemcode = '';
                  hazardBasicInfo.couse = '';
                  hazardBasicInfo.categoryname = hazardOptions.filter(
                    (item) => item.code == e,
                  )[0].name;
                }
              "
            />
          </a-form-item>
        </a-col>
        <a-col :span="7">
          <a-form-item label="项目" name="projectcode" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.projectname" disabled v-if="mode !== 'add'" />
            <a-select
              v-else
              :fieldNames="{ label: 'name', value: 'code' }"
              v-model:value="hazardBasicInfo.projectcode"
              :options="
                hazardOptions.filter(
                  (item) => item.level == 2 && item.fatherId == hazardBasicInfo.categorycode,
                )
              "
              @change="
                (e) => {
                  hazardBasicInfo.itemcode = '';
                  hazardBasicInfo.couse = '';
                  hazardBasicInfo.projectname = hazardOptions.filter(
                    (item) => item.code == e,
                  )[0].name;
                }
              "
            />
          </a-form-item>
        </a-col>
        <a-col :span="8"
          ><a-form-item label="危险源" name="itemcode" :rules="[{ required: true }]">
            <a-input v-model:value="hazardBasicInfo.itemname" disabled v-if="mode !== 'add'" />
            <a-select
              v-else
              :fieldNames="{ label: 'name', value: 'code' }"
              v-model:value="hazardBasicInfo.itemcode"
              :options="
                hazardOptions.filter(
                  (item) => item.level == 3 && item.fatherId == hazardBasicInfo.projectcode,
                )
              "
            />
          </a-form-item>
        </a-col>
        <a-col :span="11">
          <a-form-item label="是否重大危险源" name="ismajor" :rules="[{ required: true }]"
            ><a-radio-group
              v-model:value="hazardBasicInfo.ismajor"
              :disabled="mode !== 'add'"
              class="ismajorButton"
            >
              <a-radio-button :value="false">一般危险源</a-radio-button>
              <a-radio-button :value="true">重大危险源</a-radio-button>
            </a-radio-group>
          </a-form-item></a-col
        >
        <a-col :span="11">
          <a-form-item label="来源任务" name="taskitem">
            <a-select
              v-model:value="hazardBasicInfo.taskitemid"
              :options="taskOption"
              :fieldNames="{ label: 'itemname', value: 'itemid' }"
            ></a-select> </a-form-item
        ></a-col>
        <a-col :span="22"
          ><a-form-item label="事故诱因" name="couse"
            ><a-input v-model:value="hazardBasicInfo.couse" :disabled="mode !== 'add'" />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <BasicForm @register="registerIdentifyForm" style="margin-top: 5px" />
    <template #footer>
      <a-button type="primary" size="medium" @click="onButtonOkClick">完成填报</a-button>
      <a-button size="medium" @click="opSuccess">取消填报</a-button>
    </template>
  </BasicModal>
</template>

<script lang="ts">
  import { defineComponent, ref, unref, computed, onMounted, watch } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { updateIdentifyRecord, getOneIdentifyRecord } from '/@/api/ehs/hazard';
  import { updateIdentifyRecordSchema } from './hazard.data';
  import { queryEnumOption } from '/@/api/qms/exchangeData';
  import { identifyFormSchema } from './hazard.data';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import type { FormInstance } from 'ant-design-vue';
  import { queryDangerDbTreeList } from '/@/api/ehs/templateHazard';
  import { getUnitDivision } from '/@/api/ehs/unitDivision';
  import { getUnitCategory } from '/@/api/ehs/unitCategory';
  import { queryUnitTaskItem } from '/@/api/ehs/taskConsole';
  import moment from 'moment';
  const { createMessage, createInfoModal, createErrorModal } = useMessage();
  export default defineComponent({
    name: 'UpdateIdentifyRecordModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      //弹出窗口界面是新增数据、修改数据；根据传递过来的参数进行判断
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const identifyOptions = ref();
      const dataId = ref();
      const taskOption = ref([]);
      const hazardOptions = ref([]); // 当新增时,存储了可选择的当前导则库下的类别项目清单
      const hazardBasicInfo = ref({
        identifyid: '',
        unitid: '',
        unitname: '',
        categoryname: '',
        categorycode: '',
        projectname: '',
        projectcode: '',
        hazardname: '',
        hazardid: '',
        itemname: '',
        itemcode: '',
        ismajor: false,
        couse: '',
        username: '',
        tm: '',
        position: '',
        taskitemid: '',
        taskitemname: '',
      });
      const orgcode = ref<String>('');
      const [
        registerIdentifyForm,
        {
          setFieldsValue: setIdentifyValue,
          validate: validateIdentify,
          updateSchema: updateIdentifySchema,
          resetFields: resetIdentify,
        },
      ] = useForm({
        labelWidth: 130,
        schemas: identifyFormSchema,
        showActionButtonGroup: false,
        scrollToFirstError: true,
      });

      /**
       * 根据父组件传递过来的参数获取对应的操作，操作不同所对应的界面不同
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          if (unrefData?.dataId) {
            dataId.value = unrefData.dataId;
          }
          orgcode.value = unrefData.orgcode;
        }
        resetIdentify(); //重置表单
        setModalProps({ confirmLoading: false });
        getIdentifyRecordById();
      });
      /**
       * 返回弹窗标题
       */
      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });
      /**
       * 根据id获取静态信息
       */
      async function getIdentifyRecordById() {
        getOneIdentifyRecord(dataId.value)
          .then((res) => {
            res.attachment = res && res.attachment ? JSON.parse(res.attachment) : [];
            res.undercontrol = res.identificationresult == 2 ? false : true;
            let unsafefactor = [];
            if (res.undercontrol !== null && !res.undercontrol) {
              [1, 2, 4].forEach((item) => {
                if ((res.unsafefactor & item) == item) {
                  unsafefactor.push(item);
                }
              });
            }
            // 有的数据有记录,有的数据可能为null,要区分判断一下
            Object.keys(hazardBasicInfo.value).forEach((item) => {
              hazardBasicInfo.value[item] = res[item];
            });
            hazardBasicInfo.value.tm = moment(res.tm).format('YYYY-MM-DD');
            let param = res
              ? Object.keys(res)
                  .filter((key) => res[key] !== null)
                  .reduce((acc, key) => ({ ...acc, [key]: res[key] }), {})
              : {};
            setIdentifyValue({
              ...param,
              identificationresult:
                param.identificationresult == 2 ? 1 : param.identificationresult,
              unsafefactor: unsafefactor,
            });
            queryUnitTaskItem({
              unitid: hazardBasicInfo.value.unitid,
              status: 2,
              begintm: moment().startOf('year').format('YYYY-MM-DD'),
              endtm: moment().endOf('year').format('YYYY-MM-DD'),
            }).then((res) => {
              taskOption.value = res;
            });
            getUnitDivision(res.unitid).then((res1) => {
              getUnitCategory(res1.uccd).then((res2) => {
                // 新增危险源,要使用单元所在分类使用的导则库下的分类项目以及危险源信息
                queryDangerDbTreeList({ hdbcd: res2.hdbcd, keytype: 0 }).then((res) => {
                  hazardOptions.value = treeToArray(res);
                });
              });
            });
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      // tree结构扁平化
      function treeToArray(treeNodes) {
        let result = [];

        //递归函数 traverse，用于处理单个节点
        function traverse(node, fatherId) {
          const newNode = { ...node };
          if (fatherId) {
            newNode.fatherId = fatherId;
          }
          delete newNode.children;
          // 将没有子节点的新节点添加到结果数组中
          result.push(newNode);

          // 如果当前节点包含 children 属性（即有子节点）
          if (node.children) {
            node.children.forEach((item) => {
              traverse(item, newNode.code);
            });
          }
        }

        treeNodes.forEach(traverse);

        return result;
      }

      /**
       * 点击确认按钮，根据不同的op调用对应方法保存信息
       */
      async function onButtonOkClick() {
        const values = await validateIdentify();
        if (
          values.undercontrol !== undefined &&
          values.undercontrol !== null &&
          !values.undercontrol
        ) {
          values.unsafefactor = values.unsafefactor.reduce((accumulator, currentValue) => {
            return accumulator + currentValue;
          }, 0);
        }
        //验证过后的表单数据对其中的文件ID集合信息进行修改
        let fileIds = '';
        if (values.attachment && values.attachment.length > 0x0) {
          //将json对象转换为字符串
          fileIds = JSON.stringify(values.attachment);
        }
        values.attachment = fileIds;
        setModalProps({ confirmLoading: true });

        if (hazardBasicInfo.value.taskitemid) {
          hazardBasicInfo.value.taskitemname = taskOption.value.find(
            (item) => (item.itemid = hazardBasicInfo.value.taskitemid),
          ).itemname;
        }
        //调用接口进行保存
        updateIdentifyRecord({
          ...hazardBasicInfo.value,
          ...values,
          orgcode: orgcode.value,
          identificationresult:
            values.identificationresult == 1 && !values.undercontrol
              ? 2
              : values.identificationresult,
        })
          .then((res) => {
            if (res.success) {
              createInfoModal({ title: '提示', content: res.msg });
              opSuccess();
            } else {
              createErrorModal({ title: '提示', content: res.msg });
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            setModalProps({ confirmLoading: false });
          });
      }

      //操作成功后
      function opSuccess() {
        closeModal();
        emit('success');
      }

      watch(
        () => [
          hazardBasicInfo.value.couse,
          hazardBasicInfo.value.position,
          hazardBasicInfo.value.itemname,
        ],
        ([couse, position, itemname]) => {
          setIdentifyValue({
            title:
              hazardBasicInfo.value.unitname + (position ?? '') + (itemname ?? '') + (couse ?? ''),
          });
        },
      );

      onMounted(() => {
        queryEnumOptions('EhsHazardIndentificationResultTypeEnum').then((res) => {
          // console.log('option res', res);
          if (res != undefined && res != null && res.length > 0x0) {
            let op = res[0].options.map((option) => {
              return {
                value: Number(option.key),
                label: option.value,
              };
            });
            identifyOptions.value = op;
          }
        });
      });
      return {
        operateType,
        identifyOptions,
        displayModuleTitle,
        hazardBasicInfo,
        taskOption,
        registerModal,
        registerIdentifyForm,
        getIdentifyRecordById,
        onButtonOkClick,
        opSuccess,
        closeModal,
      };
    },
  });
</script>

<style scoped>
  .ant-radio-button-wrapper.ant-radio-button-wrapper-checked {
    color: #000;
  }
  .ant-radio-group-solid
    .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled):hover {
    color: #000;
  }
  .ismajorButton .ant-radio-button-wrapper:nth-child(1).ant-radio-button-wrapper-checked {
    background-color: rgb(59, 89, 153);
    color: #fff;
    border: blue;
  }
  .ismajorButton .ant-radio-button-wrapper:nth-child(2).ant-radio-button-wrapper-checked {
    background-color: rgb(205, 32, 31);
    color: #fff;
    border: red;
  }
  .ant-radio-button-wrapper-checked:not(.ant-radio-button-wrapper-disabled)::before {
    background: rgb(203, 203, 203);
  }
</style>
